package com.tedu.firstspringboot.controller;


import com.tedu.firstspringboot.util.DBUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@Controller
public class UserController {

    @RequestMapping("/userList")
    public void userList(HttpServletRequest request,HttpServletResponse response){
        System.out.println("开始处理动态页面!!!!!");
        /*
            1:从数据库中将所有用户信息查询出来
            2:将每个用户信息体现到html页面的表中的一行中
         */
        try(
            Connection connection = DBUtil.getConnection();
        ){
            String sql = "SELECT id,username,password,nickname,age FROM userinfo";
            PreparedStatement ps = connection.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            //在response.getWriter()之前设置响应头，告知浏览器正文类型和字符集，避免页面乱码
            response.setContentType("text/html;charset=utf-8");
            //通过response.getWriter()获取的缓冲字符流写出的内容会作为正文发送给浏览器
            PrintWriter pw = response.getWriter();
            pw.println("<!DOCTYPE html>");
            pw.println("<html lang=\"en\">");
            pw.println("<head>");
            pw.println("    <meta charset=\"UTF-8\">");
            pw.println("    <title>用户列表</title>");
            pw.println("</head>");
            pw.println("<body>");
            pw.println("    <center>");
            pw.println("        <h1>用户列表</h1>");
            pw.println("        <table border=\"1\">");
            pw.println("            <tr>");
            pw.println("                <td>ID</td>");
            pw.println("                <td>用户名</td>");
            pw.println("                <td>密码</td>");
            pw.println("                <td>昵称</td>");
            pw.println("                <td>年龄</td>");
            pw.println("            </tr>");
            while(rs.next()) {
                pw.println("            <tr>");
                pw.println("                <td>"+rs.getInt("id")+"</td>");
                pw.println("                <td>"+rs.getString("username")+"</td>");
                pw.println("                <td>"+rs.getString("password")+"</td>");
                pw.println("                <td>"+rs.getString("nickname")+"</td>");
                pw.println("                <td>"+rs.getInt("age")+"</td>");
                pw.println("            </tr>");
            }
            pw.println("        </table>");
            pw.println("    </center>");
            pw.println("</body>");
            pw.println("</html>");

            rs.close();//结果集释放
            ps.close();//执行计划释放

        } catch (SQLException | IOException throwables) {
            throwables.printStackTrace();
        }


    }

    @RequestMapping("/regUser")
    public void reg(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始处理注册!!!!");
        //获取表单信息
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");
        //必要验证
        if(username==null||username.isEmpty()||
            password==null||password.isEmpty()||
            nickname==null||nickname.isEmpty()||
            ageStr==null||ageStr.isEmpty()||!ageStr.matches("[0-9]+")
        ){
            //信息输入有误提示页面
            try {
                response.sendRedirect("/reg_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        System.out.println(username+","+password+","+nickname+","+ageStr);

        int age = Integer.parseInt(ageStr);
        //2 将用户信息插入到数据库的userinfo表中
        try (
                Connection connection = DBUtil.getConnection();
        ){
            //验证该用户是否存在，若存在则直接响应have_user.html,否则才执行插入操作
            String sql = "SELECT 1 FROM userinfo WHERE username=?";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1,username);
            ResultSet rs = ps.executeQuery();
            if(rs.next()){//判断结果集是否有一条记录
                response.sendRedirect("/have_user.html");
                return;
            }

            sql = "INSERT INTO userinfo (username,password,nickname,age) VALUES(?,?,?,?)";
            ps = connection.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            ps.setString(3,nickname);
            ps.setInt(4,age);
            int num = ps.executeUpdate();
            if(num>0) {
                //利用响应对象要求浏览器访问注册成功页面
                response.sendRedirect("/reg_success.html");
            }
        } catch (SQLException | IOException e) {
            e.printStackTrace();
        }

    }

    @RequestMapping("/loginUser")
    public void login(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始处理登录!!!");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username+","+password);
        //必要的验证工作
        if(username==null||username.trim().isEmpty()||
                password==null||password.trim().isEmpty()){
            try {
                response.sendRedirect("login_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        try(
            Connection connection = DBUtil.getConnection();
        ){
            // 1' OR '1'='1
            String sql = "SELECT id,username,password,nickname,age " +
                         "FROM userinfo " +
                         "WHERE username=? " +
                         "AND password=?";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                response.sendRedirect("/login_success.html");
            }else{
                //登录失败
                response.sendRedirect("/login_fail.html");
            }

        } catch (SQLException | IOException throwables) {
            throwables.printStackTrace();
        }
    }
}
